﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.Utility;

namespace FileManager_Client.PresentationLayer
{
    public partial class AddPeopleGroup : Form
    {
        private List<UserGroupResult> _userGroupResults;
        public List<UserGroupResult> ChooseUserGroup { get; set; }
        private UserService _userService;
        private static object lockWait = new object();
        private WaitDialogForm _waitBeforeLogin;
        public AddPeopleGroup()
        {
            InitializeComponent();
            _userService = new UserService();
            ChooseUserGroup = new List<UserGroupResult>();
        }

        private void BtnConfirm_Click(object sender, EventArgs e)
        {
            foreach (TreeNode treeNode in tvPeopleGroup.Nodes)
                GetCheckNode(treeNode);
            Close();
        }

        private void GetCheckNode(TreeNode node)
        {
            if (node.Checked)
                ChooseUserGroup.Add(node.Tag as UserGroupResult);
            if (node.Nodes.Count > 0)
                foreach (TreeNode subNode in node.Nodes)
                {
                    GetCheckNode(subNode);
                }
        }

        private void AddPeopleGroup_Shown(object sender, EventArgs e)
        {
            _userGroupResults =
           CacheGlobal.GetCache(GlobalString.System_Config_String.UserGroupCollectionCache) as List<UserGroupResult>;
            if (null == _userGroupResults)
            {
                SetCacheData();
                _userGroupResults =
            CacheGlobal.GetCache(GlobalString.System_Config_String.UserGroupCollectionCache) as List<UserGroupResult>;
            }
            else
            {
                var userGroupRoot = _userGroupResults.Where(x => x.Pidk__BackingField == 0);
                foreach (var userGroupResult in userGroupRoot)
                {
                    var rootNode = new TreeNode
                    {
                        Text = userGroupResult.Namek__BackingField,
                        Tag = userGroupResult
                    };
                    var subItemCollection = FindUserGroupSubItem(userGroupResult.Idk__BackingField);
                    foreach (var treeNode in subItemCollection)
                        rootNode.Nodes.Add(treeNode);
                    tvPeopleGroup.Nodes.Add(rootNode);
                }
            }
        }

        private IEnumerable<TreeNode> FindUserGroupSubItem(int groupId)
        {
            var result = new List<TreeNode>();
            var subUserGroup = _userGroupResults.Where(x => x.Pidk__BackingField == groupId);
            foreach (var userGroupResult in subUserGroup)
            {
                var subItem = new TreeNode
                {
                    Text = userGroupResult.Namek__BackingField,
                    Tag = userGroupResult
                };
                var subSubItemCollection = FindUserGroupSubItem(userGroupResult.Idk__BackingField);
                foreach (var treeNode in subSubItemCollection)
                    subItem.Nodes.Add(treeNode);
                result.Add(subItem);
            }
            return result;
        }

        private void SetCacheData()
        {
            try
            {
                lock (lockWait)
                {
                    _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.GetCompanyGroupAndUserGroup,
                                                          GlobalString.System_Config_String.MbxInfoStr)
                    {
                        BackColor = BackColor
                    };
                    _waitBeforeLogin.Hide();
                }
                var backgroundWorkerGetCompanyInfo = new BackgroundWorker();
                backgroundWorkerGetCompanyInfo.DoWork += backgroundWorkerGetCompanyInfo_DoWork;
                backgroundWorkerGetCompanyInfo.RunWorkerAsync();
                _waitBeforeLogin.ShowDialog();
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("SetCacheData has problem", ex);
                XtraMessageBox.Show("获取组织机构失败，请联系管理员!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
            }
        }

        void backgroundWorkerGetCompanyInfo_DoWork(object sender, DoWorkEventArgs e)
        {
            var result = _userService.GetCompanyGroupAndUserGroup();
            CacheGlobal.Add(GlobalString.System_Config_String.AllCompanyCollectionCache, result.CompanyResultsk__BackingField.ToList());
            CacheGlobal.Add(GlobalString.System_Config_String.CompanyGroupCollectionCache, result.CompanyGroupResultsk__BackingField.ToList());
            CacheGlobal.Add(GlobalString.System_Config_String.UserGroupCollectionCache, result.UserGroupResultsk__BackingField.ToList());
            if (!IsHandleCreated)
                CreateHandle();
            Invoke((EventHandler)delegate
            {
                _waitBeforeLogin.Close();
                _userGroupResults =
           CacheGlobal.GetCache(GlobalString.System_Config_String.UserGroupCollectionCache) as List<UserGroupResult>;
                var userGroupRoot = _userGroupResults.Where(x => x.Pidk__BackingField == 0);
                foreach (var userGroupResult in userGroupRoot)
                {
                    var rootNode = new TreeNode
                    {
                        Text = userGroupResult.Namek__BackingField,
                        Tag = userGroupResult
                    };
                    var subItemCollection = FindUserGroupSubItem(userGroupResult.Idk__BackingField);
                    foreach (var treeNode in subItemCollection)
                        rootNode.Nodes.Add(treeNode);
                    tvPeopleGroup.Nodes.Add(rootNode);
                }
            });
        }
    }
}
